package com.ztjava.auth.controller.member;

import java.util.HashMap;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.HashKit;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.ztjava.auth.Auth;
import com.ztjava.auth.model.AuthThird;
import com.ztjava.auth.model.AuthUser;
import com.ztjava.auth.service.AuthService;
import com.ztjava.auth.validator.BindingValidator;
import com.ztjava.auth.validator.ForgetValidator;
import com.ztjava.auth.validator.LoginValidator;
import com.ztjava.auth.validator.RegisterValidator;
import com.ztjava.core.Constant;
import com.ztjava.core.annotation.CustomTemplate;
import com.ztjava.core.base.BaseController;
import com.ztjava.core.tool.ViewTool;
import com.ztjava.ext.auth.annotation.UserMethod;
import com.ztjava.ext.auth.bean.AuthSession;
import com.ztjava.ext.auth.tool.AuthTool;
import com.ztjava.plugin.event.EventKit;
import com.ztjava.plugin.event.EventTag;
import com.ztjava.plugin.event.core.RequestEvent;

public class AuthMemberController extends BaseController{


	private static AuthService authService = Duang.duang(AuthService.class);
	
	/***
	 * 会员中心首页
	 */
	@CustomTemplate("index.html")
	public void index() {
		renderCustom();
	}
	/***
	 * 因为路径原因，增加个不会消失的首页
	 */
	@CustomTemplate("home.html")
	public void home() {
		renderCustom();
	}

	/***
	 * 会员登录
	 */
	@CustomTemplate("login.html")
	public void login() {
		keepPara();
		renderCustom();
	}
	
	/***
	 * 登录验证，密码错误五次请输入显示验证码
	 */
	@Before({POST.class,LoginValidator.class})
	public void doLogin() {
		AuthUser authUser = getAttr("authUser");
		AuthTool.createUserSession(authService.userToSession(authUser),3600 * 24, getResponse(),null);
		renderSuccess();
	}

	/***
	 * 注销登录
	 */
	@UserMethod
	public void logout() {
		AuthSession authSession = getAttr(Constant.AUTHSESSION);
		AuthTool.removeUserSession(authSession);
		if (Constant.XMLHttpRequest.equals(getRequest().getHeader(Constant.XRequestedWith))) {
			renderSuccess();
		} else {
			try {
				getResponse().sendRedirect("login");
			} catch (Exception e) {
				e.printStackTrace();
			}
			renderNull();
		}
		return;
	}

	/***
	 * 重置密码
	 */
	@CustomTemplate("forget.html")
	public void forget() {
		if(ViewTool.param("AUTH_MEMBER_FORGET_ONOFF","OFF").equals("OFF")){
			renderError("暂停找回密码！");
			return;
		}
		keepPara();
		renderCustom();
	}

	/***
	 * 重置密码
	 */
	@Before(ForgetValidator.class)
	public void doForget() {
		AuthUser authUser = getAttr("authUser");
		authUser.set("password", HashKit.md5(getPara("password")).toUpperCase()).update();
		renderSuccess();
	}

	/***
	 * 注册会员
	 */
	@CustomTemplate("register.html")
	public void register() {
		if(ViewTool.param("AUTH_MEMBER_REGISTER_ONOFF","OFF").equals("OFF")){
			renderError("暂停注册！");
			return;
		}
		keepPara();
		renderCustom();
	}

	/***
	 * 注册会员
	 */
	@Before(RegisterValidator.class)
	public void doRegister() {		
		String type = ViewTool.param("AUTH_MEMBER_REGISTER_TYPE");
		Map<String,String> userInfoMap = new HashMap<>();
		userInfoMap.put("password", getPara("password"));
		if(type.equals("USERNAME")){
			userInfoMap.put("username", getPara("to"));
		}else if(type.equals("EMAIL")){
			userInfoMap.put("email", getPara("to"));
			userInfoMap.put("email_auth", "T");
		}else if(type.equals("PHONE")){
			userInfoMap.put("phone", getPara("to"));
			userInfoMap.put("phone_auth", "T");
		}
		authService.insertUser(Constant.P_MEMBER, userInfoMap);
		renderSuccess();
	}

	/***
	 * 绑定会员
	 */
	@CustomTemplate("binding.html")
	public void binding() {
		keepPara();
		renderCustom();
	}
	/***
	 * 绑定会员
	 */
	@Before(BindingValidator.class)
	public void doBinding() {
		Integer third_id = getSessionAttr(Auth.SESSION_THIRD_ID);
		Map<String,String> userInfoMap = getSessionAttr(Auth.SESSION_THIRD_USER);
		AuthThird authThird = AuthThird.dao.findById(third_id);
		//是否已被注册
		AuthUser authUser = getAttr("authUser");
		String type = ViewTool.param("AUTH_MEMBER_REGISTER_TYPE");
		if(authUser==null){		
			userInfoMap.put("password", getPara("password"));
			if(type.equals("USERNAME")){
				userInfoMap.put("username", getPara("to"));
			}else if(type.equals("EMAIL")){
				userInfoMap.put("email", getPara("to"));
				userInfoMap.put("email_auth", "T");
			}else if(type.equals("PHONE")){
				userInfoMap.put("phone", getPara("to"));
				userInfoMap.put("phone_auth", "T");
			}
			authUser = authService.insertUser(Constant.P_MEMBER, userInfoMap);
		}else {
			if(type.equals("PHONE")||type.equals("EMAIL")){
				authUser.set("password",HashKit.md5(getPara("password")).toUpperCase()).update();
			}
		}
		authThird.set("user_id", authUser.getInt("id")).update();

		EventKit.postRemote(EventTag.AUTH_USER_BINDING, new RequestEvent(authThird.toRecord()));
		removeSessionAttr(Auth.SESSION_THIRD_ID);
		removeSessionAttr(Auth.SESSION_THIRD_USER);
		Cache cache = Redis.use();
		cache.hset(Constant.R_PRE+"AUTH:THIRD:"+authThird.getStr("source"), authUser.getInt("id"),authThird.getStr("code"));
		AuthTool.createUserSession(authService.userToSession(authUser),3600 * 24, getResponse(),null);
		renderSuccess();
	}
	
	
	/***
	 * 图片验证码
	 */
	public void captcha(){
		renderCaptcha();
	}

}
